package dao

import (
	"blog_server/internal/model/entity"
	"blog_server/pkg/app"
	"github.com/jinzhu/gorm"
)

func (d Dao) CreateArticle(article entity.Article) (*entity.Article, error) {
	return article.Create(d.engine)
}

func (d Dao) GetAllArticles(page, pageSize int) ([]entity.Article, error) {
	var article entity.Article
	return article.List(d.engine, app.GetPageOffset(page, pageSize), pageSize)
}

func (d Dao) GetFirstArticles(page, pageSize int) ([]entity.Article, error) {
	var article entity.Article
	return article.FirstPageArticleList(d.engine, app.GetPageOffset(page, pageSize), pageSize)
}

func (d Dao) GetArticleByID(id uint) (*entity.Article, error) {
	article := entity.Article{
		Model: &gorm.Model{
			ID: id,
		},
	}
	return article.Get(d.engine)
}

func (d Dao) CountArticles() (uint, error) {
	var article entity.Article
	return article.Count(d.engine)
}

func (d Dao) CountArticlesByClassID(id uint) (uint, error) {
	article := entity.Article{CategoryId: id}
	return article.CountByClassID(d.engine)
}

func (d Dao) GetArticlesByCategoryID(id uint, page, pageSize int) ([]entity.Article, error) {
	article := entity.Article{
		CategoryId: id,
	}
	return article.GetArticlesByCategoryID(d.engine, app.GetPageOffset(page, pageSize), pageSize)
}

func (d Dao) GetArticleListByText(text string) ([]entity.Article, error) {
	var a entity.Article
	return a.GetBySearchText(d.engine, text)
}

func (d Dao) UpdateArticle(id uint, article entity.Article, tagList []uint) error {
	err := article.UpdateById(d.engine)
	if err != nil {
		return err
	}
	ta := entity.TagArticle{ArticleId: id}
	err = ta.DeleteByArticleId(d.engine, id)
	if err != nil {
		return err
	}
	for _, tagID := range tagList {
		err = d.CreateTagArticle(tagID, article.ID)
		if err != nil {
			return err
		}
	}
	return err
}

func (d Dao) DeleteArticle(id uint) error {
	var a entity.Article
	var ta entity.TagArticle
	tx := d.engine.Begin()
	defer tx.Rollback()
	err := a.DeleteById(tx, id)
	if err != nil {
		return err
	}
	err = ta.DeleteByArticleId(tx, id)
	if err != nil {
		return err
	}
	return tx.Commit().Error
}
